package order

import (
	"gitee.com/enjoy_5/order-rpc/internal/model/product"
	proto "gitee.com/enjoy_5/order-rpc/proto/order"
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

// 订单表
type Order struct {
	gorm.Model
	OrderNo       string `gorm:"type:varchar(50);not null;unique;comment:订单编号"`
	Status        int64  `gorm:"type:tinyint(1);default:0;comment:0待付款 1待发货 2待收货 3待评价"`
	PayType       int64  `gorm:"type:tinyint(1);default:0;comment:0-支付宝 1-微信 2-余额"`
	Note          string `gorm:"type:varchar(255);comment:备注"`
	AddressId     int64  `gorm:"type:int(11);not null;comment:地址id"`
	UserId        int64  `gorm:"type:int(11);not null;comment:用户id"`
	CouponId      int64  `gorm:"type:int(11);not null;comment:优惠卷id"`
	CommentStatus int64  `gorm:"type:tinyint(1);comment:0-待审核 1-审核不通过 2-审核通过已评论"`
	Amount        string `gorm:"type:varchar(30);not null;comment:总金额"`
}

// 创建订单
func (o *Order) CreateOrder(ordergood []*proto.OrderGoodsInfo) (order *proto.OrderInfo, err error) {
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			// 创建订单
			if err := tx.Create(o).Error; err != nil {
				return err
			}

			// 准备订单商品信息
			var ordergoods []*product.OrderGoods
			for _, v := range ordergood {
				ordergoods = append(ordergoods, &product.OrderGoods{
					OrderId:  int64(o.ID),
					GoodId:   v.GoodsId,
					SkuID:    v.SkuId,
					Price:    v.Price,
					Quantity: v.Quantity,
				})
			}

			// 创建订单商品信息
			if err := tx.Create(ordergoods).Error; err != nil {
				return err
			}

			// 封装订单信息
			order = &proto.OrderInfo{
				OrderId:       int64(o.ID),
				CreateTime:    o.CreatedAt.Unix(),
				OrderNo:       o.OrderNo,
				Status:        o.Status,
				PayType:       o.PayType,
				Note:          o.Note,
				AddressId:     o.AddressId,
				UserId:        o.UserId,
				CouponId:      o.CouponId,
				Amount:        o.Amount,
				CommentStatus: o.CommentStatus,

				OrderGoodsInfo: ordergood,
			}
			return nil
		})
	})

	if err != nil {
		return nil, err
	}

	return order, nil
}

// 删除订单
func (o *Order) DeleteOrder(id, userId int64) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			err := tx.Model(o).Where("id = ? and user_id = ?", id, userId).Delete(o).Error
			if err != nil {
				return err
			}
			var goodsorder *product.OrderGoods
			err = tx.Model(&goodsorder).Where("order_id = ?", id).Delete(&goodsorder).Error
			if err != nil {
				return err
			}
			return nil
		})
	})
}

// 回滚创建订单
func (o *Order) RolDeleteOrder(orderno string, userId int64) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			var order *Order
			err := tx.Model(o).Where("order_no = ? and user_id = ?", orderno, userId).First(&order).Error
			if err != nil {
				return err
			}
			err = tx.Model(o).Where("order_no = ? and user_id = ?", orderno, userId).Delete(o).Error
			if err != nil {
				return err
			}

			var goodsorder *product.OrderGoods
			err = tx.Model(&goodsorder).Where("order_id = ?", order.ID).Delete(&goodsorder).Error
			if err != nil {
				return err
			}
			return nil
		})
	})
}

// 修改订单状态
func (o *Order) UpdateOrderStatus(id, status int64) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		err := db.Model(o).Where("id = ?", id).Update("status", status).Error
		if err != nil {
			return err
		}
		return nil
	})
}

// 查询订单列表
func (o *Order) GetOrderList(userid, status int64) ([]*proto.OrderInfo, error) {
	var orders []*Order
	var orderInfos []*proto.OrderInfo

	err := mysql.WithMysql(func(db *gorm.DB) error {
		// 构建查询条件
		query := db.Where("user_id = ?", userid)
		if status != 0 {
			query = query.Where("status = ?", status)
		}

		// 执行查询
		result := query.Find(&orders)
		if result.Error != nil {
			return result.Error
		}

		// 遍历每个订单，查询对应的订单商品信息
		for _, order := range orders {
			var orderGoods []*product.OrderGoods
			err := db.Where("order_id = ?", order.ID).Find(&orderGoods).Error
			if err != nil {
				return err
			}

			// 将 product.OrderGoods 转换为 proto.OrderGoodsInfo
			var orderGoodsInfo []*proto.OrderGoodsInfo
			for _, goods := range orderGoods {
				info := &proto.OrderGoodsInfo{
					OrderId:  goods.OrderId,
					GoodsId:  goods.GoodId,
					SkuId:    goods.SkuID,
					Price:    goods.Price,
					Quantity: goods.Quantity,
				}
				orderGoodsInfo = append(orderGoodsInfo, info)
			}

			// 构建 proto.OrderInfo 结构体
			orderInfo := &proto.OrderInfo{
				OrderId:        int64(order.ID),
				CreateTime:     order.CreatedAt.Unix(),
				OrderNo:        order.OrderNo,
				Status:         order.Status,
				PayType:        order.PayType,
				Note:           order.Note,
				AddressId:      order.AddressId,
				UserId:         order.UserId,
				CouponId:       order.CouponId,
				CommentStatus:  order.CommentStatus,
				Amount:         order.Amount,
				OrderGoodsInfo: orderGoodsInfo,
			}
			orderInfos = append(orderInfos, orderInfo)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return orderInfos, nil
}

// 查询订单详情
func (o *Order) GetOrderInfo(id int64) (*Order, error) {
	return o, mysql.WithMysql(func(db *gorm.DB) error {
		err := db.Model(o).Where("id = ?", id).First(o).Error
		if err != nil {
			return err
		}
		return nil
	})
}
